//
// Created by Administrator on 2023/4/13.
//

#ifndef WEBRTC_MODEL_STUCKTIMEPREDICTOR_H
#define WEBRTC_MODEL_STUCKTIMEPREDICTOR_H

#include <bits/stdc++.h>
#include "RandomGnerator.h"

using namespace std;

class StuckTimePredictor {
private:
    //帧率
    double avgFrameRate;
    //帧平均包个数(bit)
    double avgFramePacketCount;
    //卡顿间隔阈值
    int stuckIntervalThreshold;
    //随机生成器
    RandomGenerator<long long> randomGenerator;

    /**
     * 到达时间卡顿时间到渲染卡顿时间的映射
     * @param receiveStuckTime 到达卡顿时间
     * @return 渲染卡顿时间
     */
    static double mapReceiveStuckTimeToRenderStuckTime(double receiveStuckTime) {
        return 5.24213017e-01 * receiveStuckTime - 4.05473196e+04;
    }

public:
    long long getPredictStuckTime(long long predictPeriodMs) {
        auto totalPacketCount = static_cast<long long>((static_cast<double>(predictPeriodMs) * avgFrameRate *
                                                        avgFramePacketCount / 1000.0));
        long long predictReceiveStuckTime = 0;
        while (totalPacketCount--) {
            auto randomInterval = randomGenerator.get();
            if (randomInterval > stuckIntervalThreshold) {
                predictReceiveStuckTime += randomInterval;
            }
        }
        return static_cast<long long>(mapReceiveStuckTimeToRenderStuckTime(
                static_cast<double>(predictReceiveStuckTime)));
    }

    StuckTimePredictor(double avgFrameRate, double avgFramePacketCount, int stuckIntervalThreshold,
                       map<long long, double> &intervalDistribution) : avgFrameRate(avgFrameRate),
                                                                       avgFramePacketCount(avgFramePacketCount),
                                                                       stuckIntervalThreshold(stuckIntervalThreshold),
                                                                       randomGenerator(intervalDistribution) {}

    StuckTimePredictor(double avgFrameRate, double avgFramePacketCount, int stuckIntervalThreshold,
                       vector<pair<long long, double>> &intervalDistribution) :
            avgFrameRate(avgFrameRate),
            avgFramePacketCount(avgFramePacketCount),
            stuckIntervalThreshold(stuckIntervalThreshold),
            randomGenerator(intervalDistribution) {
        cout << stuckIntervalThreshold << endl;
    }

};

#endif //WEBRTC_MODEL_STUCKTIMEPREDICTOR_H
